package com.kmxd.ams.infra.system.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.common.collect.ImmutableSet;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.exception.BizTipException;
import com.kmxd.ams.core.exception.LogInfo;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

/**
 * 字典项
 *
 * @author ZuoLG
 * @since 2022-07-05
 */
@Data
@TableName("sys_dict_tabset")
public class SysDictTabset implements Serializable {

  private static final ImmutableSet<String> EXT_SET =
      ImmutableSet.of("ext1", "ext2", "ext3", "ext4", "ext5");

  private static final long serialVersionUID = 1L;

  /** 主键ID */
  @TableId(type = IdType.ASSIGN_ID)
  private Long id;

  /** 字典ID */
  private Long dictId;

  /** 字典项表映射列名 */
  private String fieldName;

  /** 排序 */
  private Integer sort;

  /** 备注 */
  private String remarks;

  /** 创建人 */
  @TableField(fill = FieldFill.INSERT)
  private Long createBy;

  /** 创建时间 */
  @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  @TableField(fill = FieldFill.INSERT)
  private Date createTime;

  /** 更新人 */
  @TableField(fill = FieldFill.INSERT_UPDATE)
  private Long updateBy;

  /** 更新时间 */
  @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  @TableField(fill = FieldFill.INSERT_UPDATE)
  private Date updateTime;

  public void generateSet(SysDictTabset sysDictTabsetDo, List<SysDictTabset> dbList) {
    if (null == dbList || dbList.isEmpty()) {
      sysDictTabsetDo.setFieldName("ext1");
      sysDictTabsetDo.setSort(1);
      return;
    }
    // 以扩展5个字段
    if (dbList.size() == 5) {
      throw new BizTipException(
          LogInfo.newInstance(), ErrorCode.OVER_LIMIT_NUMBER_5, "添加字典扩展，超过最大数量5");
    }
    // 找到最打的sort，新增的排序+1
    Integer maxSort =
        dbList.stream()
            .map(SysDictTabset::getSort)
            .max(Comparator.comparing(Integer::intValue))
            .orElseThrow(
                () -> new BizTipException(LogInfo.newInstance(), ErrorCode.EXCEPTION, "未找到最大的排序"));
    sysDictTabsetDo.setSort(maxSort + 1);
    // 查找未使用的ext字段，并设置
    List<String> collect =
        dbList.stream()
            .map(SysDictTabset::getFieldName)
            .filter(f -> !EXT_SET.contains(f))
            .sorted()
            .collect(Collectors.toList());
    String minFieldName = collect.get(0);
    sysDictTabsetDo.setFieldName(minFieldName);
  }
}
